package com.project.controller.web;

import com.project.entity.*;
import com.project.myBeans.ResponseBean;
import com.project.service.*;
import com.project.service.base.CrpData.CryFileUtil;
import com.project.utils.ExcelUtil;
import com.project.utils.Util;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.Class;
import java.util.*;

/**
 * author: WheelChen
 * data: 2017/6/26
 * function: 文件上传
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private CryFileUtil cryFileUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private StudentInfoService studentInfoService;

    @Autowired
    private TeacherInfoService teacherInfoService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private CvService cvService;

    @Autowired
    private SchoolService schoolService;


    public static final String deafultPassword = "123qwe";

    @RequestMapping(value = "/out", method = RequestMethod.POST)
    @ResponseBody
    /**
     * author: WheelChen
     * date: 2017/6/26
     * function: 上传公司单位外景图片
     *
     * @param file
     * @param request
     * @return
     */
    public ResponseBean out(@RequestParam("fileUp") CommonsMultipartFile file, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/static/upload/out");
            //多级地创建目录
            File f1 = new File(savePath);
            if (!f1.exists()) f1.mkdirs();

//            上传文件在服务器的文件名
            String fileName = "";

            file.getFileItem().getName();

//            获取文件格式
            String name = file.getOriginalFilename();

            String ext = name.substring(name.lastIndexOf('.'));

//            保存到服务器后的新文件名
            fileName = new Date().getTime() + ext;
//            创建文件保存对象
            File f = new File(savePath + "/" + fileName);
//            访问的绝对路径
            String fullPath = "/static/upload/out" + "/" + fileName;

//            获取文件输出流
            FileOutputStream out = new FileOutputStream(f);


//            保存文件
            FileCopyUtils.copy(file.getInputStream(), out);


//            file.getFileItem().write(f);

            System.out.println(fileName);


            responseBean.setSuccess(true);

            responseBean.setData(fullPath);

        } catch (IOException e) {
            e.printStackTrace();
            responseBean.setSuccess(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseBean;


    }

    @RequestMapping(value = "/businessliscense", method = RequestMethod.POST)
    @ResponseBody
    /**
     * author: WheelChen
     * date: 2017/6/26
     * function: 加密上传公司营业执照
     *
     * @param file
     * @param request
     * @return
     */
    public ResponseBean businessliscense(@RequestParam("fileUp") CommonsMultipartFile file, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/static/upload/businessliscense");
            //多级地创建目录
            File f1 = new File(savePath);
            if (!f1.exists()) f1.mkdirs();

//            上传文件在服务器的文件名
            String fileName = "";

            file.getFileItem().getName();

//            获取文件格式
            String name = file.getOriginalFilename();

            String ext = name.substring(name.lastIndexOf('.'));

//            保存到服务器后的新文件名
            fileName = new Date().getTime() + ext;

//            创建文件保存对象
            File f = new File(savePath + "/" + fileName);

            String fullPath = "/WEB-INF/static/upload/businessliscense" + "/" + fileName;
//            获取文件输出流
            FileOutputStream out = new FileOutputStream(f);

//             获得加密后的文件字节流
            byte[] data = cryFileUtil.encry(file.getBytes());

//            保存文件
            FileCopyUtils.copy(data, out);

//            保存文件
//            FileCopyUtils.copy(file.getInputStream(), out);

            System.out.println(fileName);

            responseBean.setSuccess(true);

            responseBean.setData(fullPath);

        } catch (IOException e) {
            e.printStackTrace();
            responseBean.setSuccess(false);
        }
        return responseBean;

    }

    @RequestMapping(value = "/addStudentBatch/{schoolId}/{departmentId}/{majorId}/{classId}", method = RequestMethod.POST)
    /**
     * author: WheelChen
     * date: 2017/6/26
     * function: Excel批量导入学生信息
     *
     * @param file
     * @return
     */
    public ResponseBean importStudentBatch(@RequestParam("fileUp") CommonsMultipartFile file, @PathVariable("schoolId") Integer schoolId,
                                                     @PathVariable("departmentId") Integer departmentId, @PathVariable("majorId") Integer majorId,
                                                     @PathVariable("classId") Integer classId, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        String name = new Date().getTime() + "导入失败数据.xlsx";
        try {
            String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/static/temp");
            //多级地创建目录
            File f1 = new File(savePath);
            if (!f1.exists()) f1.mkdirs();
            File Response = new File(savePath + "/" + name);
            Response.createNewFile();
            Map<String, List<String>> map = ExcelUtil.parse(file.getInputStream());
            Map<String, List<String>> errorData = new HashMap<>();
            errorData.put("title", map.get("0"));
            //移除第一个 （标题）
            map.remove("0");
//            //移除最后一个为空的学生
//            map.remove("" + (map.size()));
            for (Map.Entry<String, List<String>> e : map.entrySet()) {
                try {
                    System.out.println(e.getKey());
                    System.out.println(e.getValue());
                    List data = e.getValue();
                    if (data != null) {
                        User user = new User();
                        user.setUsertype(2);//账户类型设置为学生
                        user.setUsername((String) data.get(0));
                        user.setWorkid((String) data.get(0));
                        user.setRealname((String) data.get(1));
                        user.setPassword(deafultPassword);
                        //先创建用户表记录
                        //userService.createUser(user);
                        //再创建学生信息表记录
                        StudentInfo studentInfo = new StudentInfo();
                        studentInfo.setUserid(user.getId());
                        studentInfo.setSchoolid(schoolId);
                        studentInfo.setMajorid(majorId);
                        studentInfo.setDepartmentid(departmentId);
                        studentInfo.setClassid(classId);
                        //studentInfoService.add(studentInfo);
                        studentService.addDetailOne(user, studentInfo);
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                    errorData.put(e.getKey(), e.getValue());
                }

            }
            if (errorData.size() == 0){
                responseBean.setSuccess(true);
            }else {
                //创建错误数据表
                ExcelUtil.importData(Response, errorData);
                responseBean.setSuccess(false);
            }

        } catch (Exception e2) {
            e2.printStackTrace();
            responseBean.setSuccess(false);
        }
        responseBean.setData(name);
        return responseBean;
    }

    @RequestMapping(value = "/addTeacherBatch/{schoolId}/{departmentId}", method = RequestMethod.POST)
    @ResponseBody
    /**
     * author: WheelChen
     * date: 2017/6/26
     * function: Excel批量导入老师信息
     *
     * @param file
     * @param departmentId 系id
     * @param schoolId 学院id
     * @return
     */
    public ResponseBean importTeacherBatch(@RequestParam("fileUp") CommonsMultipartFile file, @PathVariable("departmentId") Integer departmentId,
                                           @PathVariable("schoolId") Integer schoolId) {
        ResponseBean responseBean = new ResponseBean();
        try {
//            List<User> users = new ArrayList<User>();
            Map<String, List<String>> map = ExcelUtil.parse(file.getInputStream());
            //移除第一个 （标题）
            map.remove("0");
            for (Map.Entry<String, List<String>> e : map.entrySet()) {
                User user = new User();
                System.out.println(e.getKey());
                System.out.println(e.getValue());
                List data = e.getValue();
                user.setUsertype(1);//账户类型设置为老师
                user.setUsername((String) data.get(0));
                user.setWorkid((String) data.get(0));
                user.setRealname((String) data.get(1));
                user.setPassword(deafultPassword);
                userService.createUser(user);
                //等等
//                users.add(user);
                TeacherInfo teacherInfo = new TeacherInfo();
                teacherInfo.setUserid(user.getId());
                teacherInfo.setDepartmentid(departmentId);
                teacherInfo.setSchoolid(schoolId);
                teacherInfoService.add(teacherInfo);
            }
//            userService.addUserBatch(users);
            responseBean.setSuccess(true);
            responseBean.setMessage("导入成功");
        } catch (Exception e) {
            responseBean.setSuccess(false);
            responseBean.setMessage("程序异常");
        }
        return responseBean;
    }

//    public ResponseBean importTeacherBatch(@RequestParam("fileUp") CommonsMultipartFile file, @RequestParam("departmentId") Integer departmentId,
//                                           @RequestParam("schoolId") Integer schoolId) {
//        ResponseBean responseBean = new ResponseBean();
//        try {
////            List<User> users = new ArrayList<User>();
//            Map<String, List<String>> map = ExcelUtil.parse(file.getInputStream());
//            //移除第一个 （标题）
//            map.remove("0");
//            for (Map.Entry<String, List<String>> e : map.entrySet()) {
//                User user = new User();
//                System.out.println(e.getKey());
//                System.out.println(e.getValue());
//                List data = e.getValue();
//                user.setUsertype(1);//账户类型设置为老师
//                user.setUsername((String) data.get(0));
//                user.setWorkid((String) data.get(0));
//                user.setRealname((String) data.get(1));
//                user.setPassword("123456");
//                userService.createUser(user);
//                //等等
////                users.add(user);
//                TeacherInfo teacherInfo = new TeacherInfo();
//                teacherInfo.setUserid(user.getId());
//                teacherInfo.setDepartmentid(departmentId);
//                teacherInfo.setSchoolid(schoolId);
//                teacherInfoService.add(teacherInfo);
//            }
////            userService.addUserBatch(users);
//            responseBean.setSuccess(true);
//            responseBean.setMessage("导入成功");
//        } catch (Exception e) {
//            responseBean.setSuccess(false);
//            responseBean.setMessage("程序异常");
//        }
//        return responseBean;
//    }

    @RequestMapping(value = "/workingpic", method = RequestMethod.POST)
    @ResponseBody
    /**
     * author: WheelChen
     * date: 2017/8/3
     * function: 上传工作环境招聘
     *
     * @param file
     * @param request
     * @return
     */
    public ResponseBean workingpic(@RequestParam("fileUp") CommonsMultipartFile file, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
//            Integer classId = Integer.getInteger(request.getParameter("classid"));
//            System.out.println(classId);
            String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/static/upload/workingpic");
            //多级地创建目录
            File f1 = new File(savePath);
            if (!f1.exists()) f1.mkdirs();

//            上传文件在服务器的文件名
            String fileName = "";

//            获取文件格式
            String name = file.getOriginalFilename();

            String ext = name.substring(name.lastIndexOf('.'));

//            保存到服务器后的新文件名
            fileName = new Date().getTime() + ext;
//            创建文件保存对象
            File f = new File(savePath + "/" + fileName);
//            访问的绝对路径
            String fullPath = "/static/upload/workingpic" + "/" + fileName;

//            获取文件输出流
            FileOutputStream out = new FileOutputStream(f);

//            保存文件
            FileCopyUtils.copy(file.getInputStream(), out);

            System.out.println(fileName);

            responseBean.setSuccess(true);

            responseBean.setData(fullPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseBean;
    }

    @RequestMapping(value = "/contract", method = RequestMethod.POST)
    @ResponseBody
    /**
     * author: WheelChen
     * date: 2017/8/6
     * function: 上传实习协议文件pdf
     *
     * @param file
     * @param userId
     * @return
     */
    public ResponseBean contract(@RequestParam("fileUp") CommonsMultipartFile file,
                                 HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/static/upload/contract");
            //多级地创建目录
            File f1 = new File(savePath);
            if (!f1.exists()) f1.mkdirs();

//            上传文件在服务器的文件名
            String fileName = "";

            file.getFileItem().getName();

//            获取文件格式
            String name = file.getOriginalFilename();

            String ext = name.substring(name.lastIndexOf('.'));

//            保存到服务器后的新文件名
            fileName = new Date().getTime() + ext;

//            创建文件保存对象
            File f = new File(savePath + "/" + fileName);

            String fullPath = "/WEB-INF/static/upload/contract" + "/" + fileName;
//            获取文件输出流
            FileOutputStream out = new FileOutputStream(f);

//             获得加密后的文件字节流
            byte[] data = cryFileUtil.encry(file.getBytes());

//            保存文件
            FileCopyUtils.copy(data, out);

//            保存文件
//            FileCopyUtils.copy(file.getInputStream(), out);———

            System.out.println(fileName);

            responseBean.setSuccess(true);

            responseBean.setData(fullPath);
        } catch (Exception e) {
            e.printStackTrace();
            responseBean.setSuccess(false);
            responseBean.setMessage("程序异常");
        }
        return responseBean;
    }

    @RequestMapping(value = "/addCv/{stId}", method = RequestMethod.POST)
    @ResponseBody
    /**
     * author: WheelChen
     * date: 2017/9/5
     * function: 上传学生简历
     *
     * @param file 简历文件
     * @param stId 学生id
     * @return
     */
    public ResponseBean cv(@RequestParam("fileUp") CommonsMultipartFile file, @PathVariable("stId") Integer stId, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            String basePath = "/WEB-INF/static/upload";

            //绝对路径
            String absolutePath = request.getSession().getServletContext().getRealPath(basePath);

            //获取用户表/学生表/学院表信息
            User user = userService.findByUserIdUnDecry(stId);
            StudentInfo studentInfo = studentInfoService.findOneByUserId(stId);
            School school = schoolService.findOne(studentInfo.getSchoolid());

            //为每个学生根据/学校id/学院id/班级id/学号 建立文件夹
            absolutePath += "/" + school.getUniversityid() +
                            "/" + school.getId() +
                            "/" + studentInfo.getClassid() +
                            "/" + user.getWorkid() + "/cv";

            //多级地创建目录
            File f1 = new File(absolutePath);

            if (!f1.exists()) f1.mkdirs();

            //上传文件在服务器的文件名
            String fileName;

//            获取文件格式
            String name = file.getOriginalFilename();
            String ext = Util.getExt(name);

//            保存到服务器后的新文件名
            fileName = new Date().getTime() + "." + ext;

//            创建文件保存对象
            File f = new File(absolutePath + "/" + fileName);

//            简历下分级目录
            String fullPath = "/" + school.getUniversityid() +
                            "/" + school.getId() +
                            "/" + studentInfo.getClassid() +
                            "/" + user.getWorkid() + "/cv" +
                            "/" + fileName;

            String URL = basePath + fullPath;

//            获取文件输出流
            FileOutputStream out = new FileOutputStream(f);

//            保存文件
            FileCopyUtils.copy(file.getInputStream(), out);

            //保存简历记录
            Cv cv = new Cv();
            cv.setFilename(fullPath);
            cv.setStid(stId);
            cvService.addOne(cv);
            System.out.println(fileName);
            System.out.println(URL);
            responseBean.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            responseBean.setSuccess(false);
            responseBean.setMessage("程序异常");
        }
        return responseBean;
    }


}
